package com.han.hotelplat.cms.controller.systemuser;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.jar.JarOutputStream;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.text.DefaultEditorKit.CutAction;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.han.hotelplat.comm.Constant;
import com.han.hotelplat.comm.ResponseWrapTo;
import com.han.hotelplat.comm.ResponseWrapTo.CodeType;
import com.han.hotelplat.comm.base.Pager;
import com.han.hotelplat.comm.utils.MD5;
import com.han.hotelplat.comm.utils.RequestUtil;
import com.han.hotelplat.comm.utils.StrUtil;
import com.han.hotelplat.comm.utils.UUIDUtils;
import com.han.hotelplat.pojo.systemuser.Permission;
import com.han.hotelplat.pojo.systemuser.Role;
import com.han.hotelplat.pojo.systemuser.Systemuser;
import com.han.hotelplat.service.systemuser.RoleService;
import com.han.hotelplat.service.systemuser.SystemuserService;

import freemarker.core.CustomAttribute;

@Controller
@RequestMapping("/cms/systemuser")
public class SystemuserController {
	@Autowired
	private SystemuserService systemuserService;
	
	@Autowired
	private RoleService roleService;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ResponseBody
	@RequestMapping(value = "401", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	private String forbidden(){
		return new ResponseWrapTo(-1, "您没有该功能的操作权限请联系管理员开通", null).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "setUserState", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	public String setUserState(String userid, Integer state){
		Systemuser user = systemuserService.findUserByUserid(userid);
		user.setState(state);
		systemuserService.update(user);
		return new ResponseWrapTo(CodeType.success, "状态修改成功", null).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "logoutRequest", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	public String logoutRequest(){
		HttpServletRequest request = RequestUtil.getRequest();
		HttpSession session = RequestUtil.getRequest().getSession(false);
		if (session != null) {
			Enumeration<String> keys = request.getSession().getAttributeNames();
			while (keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				request.getSession().removeAttribute(key);
			}
			Cookie[] cookies = request.getCookies();
			for (Cookie cookie : cookies) {
				cookie.setMaxAge(0);
			}
			Subject currentUser = SecurityUtils.getSubject();
			currentUser.logout();
		}
		return new ResponseWrapTo(CodeType.success, "用户退出成功", null).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "addRole", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	public String addRole(Integer roleid, String rolename, String permissionList){
		List<Permission> li = systemuserService.findAllPermissions();
		JSONArray jarry = JSONArray.parseArray(permissionList);
		List<Permission> newdata = new ArrayList<Permission>();
		for(Permission p : li){
			for (Object id : jarry) {
				if(p.getPermissionid().intValue() == Integer.parseInt(id.toString())){
					newdata.add(p);
				}
			}
		}
		Role data = null;
		if(roleid != null && roleid.intValue()>0){
			Role r = roleService.findRoleById(roleid);
			if(!StrUtil.isNullOrEmpty(rolename)){
				r.setRolename(rolename);
			}
			r.setPermissions(newdata);
			roleService.update(r);
			data = r;
		}
		if(roleid == null){
			Role r = new Role(rolename, (short)1);
			r.setPermissions(newdata);
			roleService.save(r);
			data = r;
		}
		Role role = new Role(data.getRoleid(), data.getRolename(), data.getIsvalid());
		List<Permission> pli = data.getPermissions();
		List<Permission>newpli = new ArrayList<Permission>();
		for(Permission permission : pli){
			Permission p = new Permission(permission.getPermissionid(), 
					permission.getName(), permission.getUrl(), 
					permission.getPermission(), permission.getGroupid());
			newpli.add(p);
		}
		role.setPermissions(newpli);
		return new ResponseWrapTo(CodeType.success, "角色新增成功", role).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "getAllPermission", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	private String getAllPermission(){
		List<Permission> data = systemuserService.findAllPermissions();
		List<Permission>li = new ArrayList<Permission>();
		for(Permission permission : data){
			Permission p = new Permission(permission.getPermissionid(), 
					permission.getName(), permission.getUrl(), 
					permission.getPermission(), permission.getGroupid());
			li.add(p);
		}
		return new ResponseWrapTo(CodeType.success, "数据获取成功", li).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "getAllRole", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	private String getAllRole(){
		List<Role> data = roleService.findAllRole();
		List<Role>li = new ArrayList<Role>();
		for(Role r : data){
			Role role = new Role(r.getRoleid(), r.getRolename(), r.getIsvalid());
			List<Permission> pli = r.getPermissions();
			List<Permission>newpli = new ArrayList<Permission>();
			for(Permission permission : pli){
				Permission p = new Permission(permission.getPermissionid(), 
						permission.getName(), permission.getUrl(), 
						permission.getPermission(), permission.getGroupid());
				newpli.add(p);
			}
			role.setPermissions(newpli);
			li.add(role);
		}
		return new ResponseWrapTo(CodeType.success, "数据获取成功", li).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "getAllSystemuser", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	private String getAllSystemuser(Integer areaCode, Integer roleId, String condition, Integer pageNo){
		Pager<Systemuser> data = systemuserService.getAllSystemuserByPage(areaCode,roleId,condition,pageNo);
		return new ResponseWrapTo(CodeType.success, "数据获取成功", data).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "login", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	public String login(String username, String password){
		try{
			Systemuser u = systemuserService.findUserByUsernam(username);
			if(u != null && u.getState() != null && u.getState().intValue() == 2){
				return new ResponseWrapTo(CodeType.fail, "已离职", null).toJson();
			}
			UsernamePasswordToken token = new UsernamePasswordToken(username,password);
			Subject currentUser = SecurityUtils.getSubject();
			currentUser.login(token);
			RealmSecurityManager rsm =  (RealmSecurityManager) SecurityUtils.getSecurityManager();
			ShiroDataBaseRealm userRealm  = (ShiroDataBaseRealm) rsm.getRealms().iterator().next();  
			System.out.println("用户<"+username+">登录成功");
			Iterator its = currentUser.getPrincipals().fromRealm("ShiroDataBaseRealm").iterator();
	        if (its.hasNext() == false) {
	            throw new AuthorizationException("找不到User啊，登录失败？");
	        }
	        userRealm.clearAuthz();
	        Systemuser user = (Systemuser) its.next();
			systemuserService.update(user);
			List<Role> roles = user.getRoles();
			Role r = user.getRoles().size()>0?user.getRoles().get(0):null;
			user.setRoles(null);
			user.setRoleid(r.getRoleid());
			user.setRolename(r.getRolename());
			RequestUtil.setSessionAttribute(Constant.CMS_SESSION_LOGIN_USER, user);
			String userjs = JSONObject.toJSONString(user);
			user.setRoles(roles);
			return new ResponseWrapTo(CodeType.success, "登陆成功", JSONObject.parse(userjs)).toJson();
		}catch(AuthenticationException ae){
			ae.printStackTrace();
			return new ResponseWrapTo(CodeType.fail, "登陆失败", null).toJson();
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "creatCMSUser", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	public String creatCMSUser(Integer id, String realname,String department,
			Integer roleid,String tel, String username, String password){
		Systemuser user = null;
		user = systemuserService.findUserByTel(tel);
		if(user != null && id == null){
			return new ResponseWrapTo(-1, "手机号已经存在", null).toJson();
		}
		user = systemuserService.findUserByUsernam(username);
		if(user != null && id == null){
			return new ResponseWrapTo(-1, "用户名已经存在", null).toJson();
		}
		
		if(id != null){
			user.setVocation("leader");//普通身份
			user = systemuserService.findUserById(id);
			user.setUserid(UUIDUtils.getUUID()+"");
			user.setRealname(realname);
			user.setDepartment(department);
			user.setTel(tel);
			if(!StrUtil.isNullOrEmpty(password)){
				user.setPassword(MD5.toMD5(password));
			}
			user.setUsername(username);
			List<Role> roles = user.getRoles();
			if(roles != null && roles.size()>0){
				Role r = roles.get(0);
				if(r.getRoleid().intValue() != roleid){//修改了角色ID
					Role newrole = roleService.findRoleById(roleid);
					List<Role> newroles = new ArrayList<Role>();
					newroles.add(newrole);
					user.setRoles(newroles);
				}
				user.setRolename(r == null ? "":r.getRolename());
				user.setRoleid(r == null ? -1 :r.getRoleid());
			}
			systemuserService.update(user);
			Systemuser u = new Systemuser();
			u.setUserid(user.getUserid());
			u.setUsername(user.getUsername());
			u.setRealname(user.getRealname());
			u.setDepartment(user.getDepartment());
			u.setTel(user.getTel());
			u.setPassword(null);
			u.setRolename(user.getRolename());
			u.setRoleid(user.getRoleid());
			return new ResponseWrapTo(0, "更新成功", u).toJson();
		}
		user = new Systemuser();
		user.setVocation("leader");//普通身份
		user.setUserid(UUIDUtils.getUUID()+"");
		user.setRealname(realname);
		user.setDepartment(department);
		user.setTel(tel);
		user.setUsername(username);
		user.setPassword(MD5.toMD5(password));
		user.setCreattime(new Date());
		Role r = roleService.findRoleById(roleid);
		List<Role> roles = new ArrayList<Role>();
		roles.add(r);
		user.setRoles(roles);
		user.setState(1);//在职状态
		systemuserService.creatCMSUser(user);
		Systemuser u = new Systemuser();
		u.setUserid(user.getUserid());
		u.setUsername(user.getUsername());
		u.setRealname(user.getRealname());
		u.setDepartment(user.getDepartment());
		u.setRolename(r == null ? "":r.getRolename());
		u.setTel(user.getTel());
		u.setPassword(null);
		return new ResponseWrapTo(0, "创建成功", u).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "updateCMSUserMe", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	public String updateCMSUserMe(String realname,String tel, String password){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		Systemuser olduser = systemuserService.findUserByTel(tel);
		
		if(!StringUtils.isNotBlank(realname) && !StringUtils.isNotBlank(tel) && StringUtils.isNotBlank(password)){
			return new ResponseWrapTo(-1, "资料不全", null).toJson();
		}
		if(olduser != null && !tel.equals(user.getTel())){
			return new ResponseWrapTo(-1, "手机号已经存在", null).toJson();
		}
		
		systemuserService.findUserByUserid(user.getUserid());	
		user.setRealname(realname);
		user.setTel(tel);
		user.setPassword(MD5.toMD5(password));
		systemuserService.update(user);
		
		Systemuser u = new Systemuser();
		u.setUserid(user.getUserid());
		u.setUsername(user.getUsername());
		u.setRealname(user.getRealname());
		u.setDepartment(user.getDepartment());
		u.setTel(user.getTel());
		u.setPassword(null);
		u.setRolename(user.getRolename());
		u.setRoleid(user.getRoleid());
		return new ResponseWrapTo(0, "更新成功",u).toJson();
	}
	
	
	/**account/logout
	 * logout
	 */
	@RequestMapping(value = "logout", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public String logout(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			Enumeration<String> keys = request.getSession().getAttributeNames();
			while (keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				request.getSession().removeAttribute(key);
			}
			Cookie[] cookies = request.getCookies();
			for (Cookie cookie : cookies) {
				cookie.setMaxAge(0);
			}
		}
		return new ResponseWrapTo(CodeType.success,"退出成功",null).toJson();
	}
	
}
